package com.yjs.app.trade.service.service.util;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.google.common.collect.Lists;
import com.yjs.app.trade.core.util.HttpUtils;
import com.yjs.app.trade.core.util.PropertiesUtils;
import com.yjs.app.trade.core.util.StringUtils;
import com.yjs.app.trade.service.service.business.member.MemberService;
import com.yjs.app.trade.service.service.business.order.OrderService;
import com.yjs.app.trade.service.service.sys.MessagePushService;
import com.yjs.app.trade.service.service.sys.UserService;

import net.sf.json.JSONObject;

@Component
public class UtilService {
	@Autowired
	OrderService orderService;
	@Autowired
	MemberService memberService;
	@Autowired
	MessagePushService messagePushService;
	@Autowired
	UserService userService;
	static Logger log = LoggerFactory.getLogger(Logger.class);

	public static String host = PropertiesUtils.getProperty("push.host");
	public static String port = PropertiesUtils.getProperty("push.port");
	public static String project = PropertiesUtils.getProperty("push.project");
	public static String path = PropertiesUtils.getProperty("push.path");
	public static String method = PropertiesUtils.getProperty("push.method");

	static Map<Integer, Integer> map = new HashMap<>();

	@SuppressWarnings("unchecked")
	public void reviceMessages(List<JSONObject> msgs) {
		int type = 0;
		if (JSONObject.fromObject(msgs.get(0)).get("orderDetails") != null) {
			type = 2;
		} else if (JSONObject.fromObject(msgs.get(0)).get("contractDetails") != null) {
			type = 1;
		}
		String tagNo = "";
		try {
			for (JSONObject string : msgs) {
				if (type == 1) {
					tagNo = string.getString("contractId");
					this.saveMessage("{\"messageType\":\"" + type + "\", \"messageNumber\": \"" + tagNo + "\"}");
				} else if (type == 2) {
					List<JSONObject> orderDetails = string.getJSONArray("orderDetails");
					for (JSONObject orderDetail : orderDetails) {
						tagNo = orderDetail.getString("orderDetailNo");
						this.saveMessage("{\"messageType\":\"" + type + "\", \"messageNumber\": \"" + tagNo + "\"}");
					}
				}
			}
		} catch (Exception e) {
			log.error("解析kafka推送消息~~~~" + type + "---------" + e);
		}
	}

	/**
	 * 解析RabbitMQ消息
	 * 
	 * @param message
	 */
	public void reviceMsgByRabbit(String message) {
		JSONObject jsonObject = JSONObject.fromObject(message);
		String msgNo = (String) jsonObject.get("msgNumber");
		int type = 0;
		if (jsonObject.get("msgType") != null) {
			Integer msgtype = Integer.parseInt(jsonObject.get("msgType").toString());
			if (msgtype == 1) {
				type = 2;
			} else if (msgtype == 2) {
				type = 1;
			} else {
				type = msgtype;
			}
		}
		try {
			if (type == 1) {
				this.saveMessage("{\"messageType\":\"" + type + "\", \"messageNumber\": \"" + msgNo
						+ "\", \"msgState\": \"" + jsonObject.get("msgState").toString() + "\"}");
			} else if (type == 2) {
				List<Map<String, String>> findOrderNumber = orderService.findOrderNumber(msgNo);
				for (Map<String, String> map : findOrderNumber) {
					String msgNumber = map.get("orderNumber");
					this.saveMessage("{\"messageType\":\"" + type + "\", \"messageNumber\": \"" + msgNumber
							+ "\", \"msgState\": \"" + jsonObject.get("msgState").toString() + "\"}");
				}
			} else {
//				log.info("------gmp,议价消息......type:"+type+"messageNumber"+msgNo+"msgState"+jsonObject.get("msgState").toString());
//				log.info("sellerID"+jsonObject.get("userID").toString());
				this.saveMessage("{\"messageType\":\"" + type + "\", \"messageNumber\": \"" + msgNo
						+ "\", \"msgState\": \"" + jsonObject.get("msgState").toString() + "\", \"sellerId\": \""
						+ jsonObject.get("userID").toString() + "\"}");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("解析RabbitMQ推送消息~~~~" + type + "---------" + e);
		}

	}
	public void saveMessage(String str) throws UnknownHostException {
		JSONObject jsonObject = JSONObject.fromObject(str);
		// Map<String, Object> map = new HashMap<String, Object>();
		String number =jsonObject.getString("messageNumber");// 获得编号
		int type = jsonObject.getInt("messageType");// 获得消息类型
		Integer status = 0;
		if(jsonObject.get("msgState") != null){
			status = jsonObject.getInt("msgState");// 获得消息状态
//			log.info("消息状态"+status.toString());
		}
		String buyerId = "";
		String sellerId = "";
		String dispatchId = "";
		Map<String, Object> result = null;
		if (type == 1) {
			result = memberService.findMemenberId(number);
			//log.info("RESULT:"+result.toString()+"NUMBER:"+number);
		} else if (type == 2) {
			result = orderService.findOrderMemberId(number);
		} else if (type == 7 || type == 8 || type == 9 || type == 10) {
			// 如果为GMP/议价消息.....
			int lastMessageNum = messagePushService.checkTagIsPush(number, status);
			if (lastMessageNum > 0) {
				return;
			}
			String message = this.getTagMessageByStatus(status,type);
//			log.info("组装消息:"+message+"status,type:"+status+" "+type);
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("sellerId", jsonObject.getString("sellerId"));
			this.saveMessage(number, type, status, message, param);
		}
		if (result != null && result.size() > 0) {
		
			buyerId = (String) result.get("buyerId");
			sellerId = (String) result.get("sellerId");
			dispatchId = (String) result.get("dispatchId");
			if(status == null || status.equals("")){
			status = Integer.parseInt(result.get("status").toString());
			}
		} else {
			return;
		}
		String message = this.getTagMessageByStatus(status, number, type);
		
//		log.info("判断消息是否为空"+message+ " " + number + " " + status+" "+type);
		if (!StringUtils.strIsNotNull(message)) {
			return;
		}
		int lastMessageNum = messagePushService.checkTagIsPush(number, status);
//		log.info("判断lastMessageNum是否为空"+lastMessageNum );
		if (lastMessageNum > 0) {
			return;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("buyerId", buyerId);
		param.put("sellerId", sellerId);
		param.put("dispatchId", dispatchId);
		this.saveMessage(number, type, status, message, param);
	}

	private void saveMessage(String number, int type, Integer status, String message, Map<String, Object> param) {
		Map<String, Object> map = null;
		//log.info("param:"+param.toString());
		List<Map<String, Object>> passportInfos = userService.findPassportIdByMemberId(param);
		//log.info("passportInfos:"+passportInfos.toString());
		if (passportInfos != null && passportInfos.size() > 0) {
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			List<String> arry = new ArrayList<>();
			String buyerIdC=(String) param.get("buyerId");
			param.clear();
			for (int i = 0; i < passportInfos.size(); i++) {
				List<Map<String, Object>> passportMaps = userService.getPassportSalesAut(passportInfos.get(i).get("passportId").toString());
//				log.info("查询关联关系:"+passportMaps.toString());
				List<String> memberIds = new ArrayList<>();
				for (Map<String, Object> map2 : passportMaps) {
					if (map2.get("memberId") != null) {
						memberIds.add(map2.get("memberId").toString());
					}
				}
				if (passportMaps.get(0).get("adminPassportId") != null || memberIds.contains(buyerIdC)) {
					map = new HashMap<String, Object>();
					map.clear();
					map.put("messageType", type);
					map.put("ischeck", 1);
					map.put("messageContent", message);
					map.put("messageNumber", number);
					map.put("status", status);
					map.put("created", new Date());
					String id = UUID.randomUUID().toString().replace("-", "");
					map.put("id", id + i);
					param = passportInfos.get(i);
					map.put("passportId", param.get("passportId"));
					list.add(map);
//					log.info(this.isSendJPushMessage(passportInfos.get(i), type, status)+"   "+StringUtils.strIsNotNull(passportInfos.get(i).get("jpushId"))+"  "+passportInfos.get(i).get("jpushId"));
					if (this.isSendJPushMessage(passportInfos.get(i), type, status) && StringUtils.strIsNotNull(passportInfos.get(i).get("jpushId"))) {
						arry.add((String) passportInfos.get(i).get("jpushId"));
					}
				}
			}
			if (list != null && list.size() > 0) {
				int result = messagePushService.saveMessagePush(list);
				if (result > 0 && arry != null && arry.size() > 0) {
					getTime(arry, message);
				}
			}
		}
	}

	public static void getTime(List<String> list, String message) {
	//	log.info("getTime>>>>>>>>>>");
		Map<String, String> querys = new HashMap<String, String>();
		Map<String, String> header = new HashMap<String, String>();
		String body = "";
		querys.put("message", message);
		List<List<String>> lists = UtilService.split(list, 550);
		StringBuffer jpushIds = new StringBuffer();
		for (List<String> li : lists) {
			Calendar calendar = Calendar.getInstance();
			int time = calendar.get(Calendar.MINUTE);
			if (map.get(time) != null) {
				if (map.get(time) + li.size() <= 600) {
					map.put(time, map.get(time) + li.size());
					for (String string : li) {
						if (StringUtils.isNotBlank(jpushIds.toString())) {
							jpushIds.append("," + string);
						} else {
							jpushIds.append(string);
						}
					}
	//				log.info("这是JupushID"+jpushIds.toString());
					querys.put("jpushIds", jpushIds.toString());
					try {
						HttpUtils.doPost(host + ":" + port + project, path, method, header, querys, body);
					} catch (Exception e) {
						e.printStackTrace();
					}
					querys.clear();
					jpushIds.delete(0, jpushIds.length());
				} else {
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					getTime(li, message);
				}
			} else {
				map.clear();
				map.put(time, li.size());
				for (String string : li) {
					if (StringUtils.isNotBlank(jpushIds.toString())) {
						jpushIds.append("," + string);
					} else {
						jpushIds.append(string);
					}
				}
				querys.put("jpushIds", jpushIds.toString());
				try {
					HttpUtils.doPost(host + ":" + port, project + path, method, header, querys, body);
				} catch (Exception e) {
					e.printStackTrace();
				}
				querys.clear();
				jpushIds.delete(0, jpushIds.length());
			}
		}
	}

	public static <T> List<List<T>> split(List<T> reslist, int subListLength) {
		if (CollectionUtils.isEmpty(reslist) || subListLength <= 0) {
			return Lists.newArrayList();
		}
		List<List<T>> ret = Lists.newArrayList();
		int size = reslist.size();
		if (size <= subListLength) {
			// 数量不足subListLength指定大小
			ret.add(reslist);
		} else {
			int pre = size / subListLength;
			int last = size % subListLength;
			// 前面pre个集合,每个大小都是subListlength个元素
			for (int i = 0; i < pre; i++) {
				List<T> itemList = Lists.newArrayList();
				for (int j = 0; j < subListLength; j++) {
					itemList.add(reslist.get(i * subListLength + j));
				}
				ret.add(itemList);
			}
			// last的进行处理
			if (last > 0) {
				List<T> itemList = Lists.newArrayList();
				for (int i = 0; i < last; i++) {
					itemList.add(reslist.get(pre * subListLength + i));
				}
				ret.add(itemList);
			}
		}
		return ret;

	}
	/**
	 * 没有编号的消息组装
	 * @param status
	 * @param type
	 * @return
	 */
	public String getTagMessageByStatus(int status,int type) {
		String tagName = "";
		String statusName = "";
		switch (type) {
		case 7:
			tagName = "议价";
			switch (status) {
			case 0:
				statusName = "待发送";
				break;
			case 1:
				statusName = "议价中";
				break;
			case 3:
				statusName = "成功";
				break;
			case 4:
				statusName = "失败";
				break;
			case 6:
				statusName = "新增";
				break;
			default:
				return "议价状态改变";
			}
			break;
		case 8:
			tagName = "GMP";
			switch (status) {
			case 1:
				statusName = "到期";
				break;
			case 2:
				statusName = "审核通过";
				break;
			case 3:
				statusName = "审核不通过";
				break;
			default:
				return "GMP状态改变";
			}
			break;
		case 9:
			tagName = "进口代理协议";
			switch (status) {
			case 1:
				statusName = "到期";
				break;
			case 4:
				statusName = "审核通过";
				break;
			case 5:
				statusName = "审核不通过";
				break;
			default:
				return "进口代理协议状态改变";
			}
			break;
		case 10:
			tagName = "产品审核";
			switch (status) {
			case 8:
				statusName = "审核通过";
				break;
			case 9:
				statusName = "审核不通过";
				break;
			default:
				return "产品审核状态改变";
			}
			break;
		default:
		} 
		return tagName+"--"+statusName;
	}

	public String getTagMessageByStatus(int status, String tagId, int type) {
		String tagName = "";
		String statusName = "";
		switch (type) {
		case 1:
			tagName = "合同";
			switch (status) {
			case 1:
				statusName = "待响应";
				break;
			case 2:
				statusName = "已响应";
				break;
			case 3:
				statusName = "已出库";
				break;
			case 4:
				statusName = "已完结";
				break;
			case 5:
				statusName = "已失效";
				break;
			case 6:
				statusName = "待收货";
				break;
			case 7:
				statusName = "卖方已响应";
				break;
			case 8:
				statusName = "配送方已响应";
				break;
			default:
				return "";
			}
			break;
		case 2:
			tagName = "订单";
			switch (status) {
			case 1:
				statusName = "待响应";
				break;
			case 2:
				statusName = "响应";
				break;
			case 3:
				statusName = "出库";
				break;
			case 4:
				statusName = "完结";
				break;
			case 5:
				statusName = "失效";
				break;
			case 6:
				statusName = "待收货";
				break;
			case 7:
				statusName = "卖方已响应";
				break;
			case 8:
				statusName = "配送方已响应";
				break;
			default:
				return "";
			}
			break;
		default:
			return "";
		}
		return tagName + "号:" + tagId + "已" + statusName;
	}

	public boolean isSendJPushMessage(Map<String, Object> maps, int type, int status) {
//		log.info("判断是否推送消息------"+maps.toString()+"---"+type+"---"+status);
		if (type == 1) {
			if (status == 1) {
				if (maps.get("isNewContract") != null && Integer.parseInt(maps.get("isNewContract").toString()) == 1) {
					return true;
				} 
			} else if (status == 2 || status == 3 || status == 4 || status == 6 || status == 7 || status == 8) {
				
				if (maps.get("isContractStatus") != null && Integer.parseInt(maps.get("isContractStatus").toString()) == 1) {
					return true;
				}
			} else if (status == 5) {
				if (maps.get("isExpirationContract") != null
						&& Integer.parseInt(maps.get("isExpirationContract").toString()) == 1) {
					return true;
				}
			}
		} else if (type == 2) {
			if (status == 1) {
				if (maps.get("isNewOrder") != null && Integer.parseInt(maps.get("isNewOrder").toString()) == 1) {
					return true;
				}
			} else if (status == 4 || status == 5) {
				if (maps.get("isOrderAog") != null && Integer.parseInt(maps.get("isOrderAog").toString()) == 1) {
					return true;
				}
			} else {
				if (maps.get("isOrderStatus") != null && Integer.parseInt(maps.get("isOrderStatus").toString()) == 1) {
					return true;
				}
			}
		}else if (type == 7) {
			if (maps.get("isBargain") != null && Integer.parseInt(maps.get("isBargain").toString()) == 1) {
					return true;
			}
		}
		else if (type == 8) {
			if (maps.get("isGmp") != null && Integer.parseInt(maps.get("isGmp").toString()) == 1) {
					return true;
			}
		}
		else if (type == 9) {
			if (maps.get("isImportAgencyAgreement") != null && Integer.parseInt(maps.get("isImportAgencyAgreement").toString()) == 1) {
					return true;
			}
		}else if (type == 10) {
			if (maps.get("isProductAudit") != null && Integer.parseInt(maps.get("isProductAudit").toString()) == 1) {
					return true;
			}
		}
		return false;

	}
	
	public static void main(String[] args) {
		List<String> list=new ArrayList<>();
		list.add("100d8559093c99a8a62");
		list.add("100d8559090229bd5ab");
		list.add("140fe1da9edede11125");
		UtilService.getTime(list, "sdada");
	}

}
